/**
* @project admin-go-api
* @name ISysAdminService
* @descriptions
* @author 寒锋
* @date 2023-12-14 17:23:14
 */

package service

import (
	"admin-go-api/api/dao"
	"admin-go-api/api/entity"
	"admin-go-api/common/response"
	"admin-go-api/common/util"
	"admin-go-api/constants"
	"admin-go-api/pkg/jwt"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

// ISysAdminService 定义接口
type ISysAdminService interface {
	GetSysAdminList(c *gin.Context, PageNum, PageSize int, Username, Nickname string, Status int, BeginTime, EndTime string)
	CreateSysAdmin(c *gin.Context, dto entity.StoreSysAdminDto)
	GetSysAdminById(c *gin.Context, adminId int)
	UpdateSysAdmin(c *gin.Context, dto entity.UpdateSysAdminDto)
	UpdateSysAdminState(c *gin.Context, dto entity.UpdateSysAdminStateDto)
	DeleteSysAdminById(c *gin.Context, dto entity.SysAdminIdDto)
	ResetSysAdminPassword(c *gin.Context, dto entity.ResetSysAdminPasswordDto)
	UpdatePersonal(c *gin.Context, dto entity.UpdatePersonalDto)
	UpdatePersonalPassword(c *gin.Context, dto entity.UpdatePersonalPasswordDto)
}

type SysAdminServiceImpl struct{}

// GetSysAdminList 管理员列表
func (s SysAdminServiceImpl) GetSysAdminList(c *gin.Context, PageNum, PageSize int, Username, Nickname string, Status int, BeginTime, EndTime string) {
	list, count := dao.GetSysAdminList(PageNum, PageSize, Username, Nickname, Status, BeginTime, EndTime)
	data := map[string]interface{}{"total": count, "pageNum": PageNum, "pageSize": PageSize, "rows": list}
	response.Success(c, data)
}

// CreateSysAdmin 添加管理员
func (s SysAdminServiceImpl) CreateSysAdmin(c *gin.Context, dto entity.StoreSysAdminDto) {
	// 验证参数
	err := validator.New().Struct(dto)
	if err != nil {
		response.Failed(c, int(constants.ApiCode.MissingNewAdminParameter), constants.ApiCode.GetMessage(constants.ApiCode.MissingNewAdminParameter))
		return
	}
	// 验证管理员是否已存在
	userName := dao.GetSysAdminByName(dto.Username, 0)
	if userName.AdminId > 0 {
		response.Failed(c, int(constants.ApiCode.UserNameAlreadyExists), constants.ApiCode.GetMessage(constants.ApiCode.UserNameAlreadyExists))
		return
	}
	err = dao.CreateSysAdmin(dto)
	if err != nil {
		response.Failed(c, int(constants.ApiCode.FAILED), fmt.Sprintf("添加失败（%s）", err.Error()))
		return
	}
	response.Success(c, nil)
}

// GetSysAdminById 管理员详情
func (s SysAdminServiceImpl) GetSysAdminById(c *gin.Context, adminId int) {
	row := dao.GetSysAdminInfoById(adminId)
	response.Success(c, row)
}

// UpdateSysAdmin 修改管理员
func (s SysAdminServiceImpl) UpdateSysAdmin(c *gin.Context, dto entity.UpdateSysAdminDto) {
	s.checkAdminIsExists(c, int(dto.AdminId))
	// 验证管理员是否已存在
	userName := dao.GetSysAdminByName(dto.Username, int(dto.AdminId))
	if userName.AdminId > 0 {
		response.Failed(c, int(constants.ApiCode.UserNameAlreadyExists), constants.ApiCode.GetMessage(constants.ApiCode.UserNameAlreadyExists))
		return
	}
	err := dao.UpdateSysAdmin(dto)
	if err != nil {
		response.Failed(c, int(constants.ApiCode.FAILED), fmt.Sprintf("更新失败（%s）", err.Error()))
		return
	}
	response.Success(c, nil)
}

// UpdateSysAdminState 修改管理员状态
func (s SysAdminServiceImpl) UpdateSysAdminState(c *gin.Context, dto entity.UpdateSysAdminStateDto) {
	s.checkAdminIsExists(c, int(dto.AdminId))
	result := dao.UpdateSysAdminState(dto)
	if result {
		response.Success(c, nil)
		return
	}
	response.Failed(c, int(constants.ApiCode.FAILED), "修改失败")
}

// DeleteSysAdminById 删除管理员
func (s SysAdminServiceImpl) DeleteSysAdminById(c *gin.Context, dto entity.SysAdminIdDto) {
	s.checkAdminIsExists(c, int(dto.AdminId))
	err := dao.DeleteSysAdmin(int(dto.AdminId))
	if err != nil {
		response.Failed(c, int(constants.ApiCode.FAILED), fmt.Sprintf("删除失败（%s）", err.Error()))
		return
	}
	response.Success(c, nil)
}

// ResetSysAdminPassword 重置密码
func (s SysAdminServiceImpl) ResetSysAdminPassword(c *gin.Context, dto entity.ResetSysAdminPasswordDto) {
	s.checkAdminIsExists(c, int(dto.AdminId))
	result := dao.ResetSysAdminPassword(dto)
	if result {
		response.Success(c, nil)
		return
	}
	response.Failed(c, int(constants.ApiCode.FAILED), "密码重置失败")
}

// UpdatePersonal 修改个人信息
func (s SysAdminServiceImpl) UpdatePersonal(c *gin.Context, dto entity.UpdatePersonalDto) {
	err := validator.New().Struct(dto)
	if err != nil {
		response.Failed(c, int(constants.ApiCode.MissingModificationOfPersonalParameters), constants.ApiCode.GetMessage(constants.ApiCode.MissingModificationOfPersonalParameters))
		return
	}
	adminId, _ := jwt.GetAdminId(c)
	dto.AdminId = adminId
	result := dao.UpdatePersonal(dto)
	if result {
		response.Success(c, nil)
		return
	}
	response.Failed(c, int(constants.ApiCode.FAILED), "修改个人信息失败")
}

// UpdatePersonalPassword 修改个人密码
func (s SysAdminServiceImpl) UpdatePersonalPassword(c *gin.Context, dto entity.UpdatePersonalPasswordDto) {
	err := validator.New().Struct(dto)
	if err != nil {
		response.Failed(c, int(constants.ApiCode.MissingChangePasswordParameter), constants.ApiCode.GetMessage(constants.ApiCode.MissingChangePasswordParameter))
		return
	}
	sysAdmin, _ := jwt.GetAdmin(c)
	dto.AdminId = sysAdmin.AdminId
	sysAdminExists := dao.GetSysAdminByName(sysAdmin.Username, 0)
	if sysAdminExists.Password != util.EncryptionMd5(dto.Password) {
		response.Failed(c, int(constants.ApiCode.PasswordNotTrue), constants.ApiCode.GetMessage(constants.ApiCode.PasswordNotTrue))
		return
	}
	if dto.NewPassword != dto.ResetPassword {
		response.Failed(c, int(constants.ApiCode.ResetPassword), constants.ApiCode.GetMessage(constants.ApiCode.ResetPassword))
		return
	}
	result := dao.UpdatePersonalPassword(dto)
	if result {
		// 修改密码后，重新生成token
		sysAdminUpdatePwd := dao.GetSysAdminById(int(dto.AdminId))
		tokenString, _ := jwt.GenerateTokenByAdmin(sysAdminUpdatePwd)
		data := map[string]interface{}{"token": tokenString, "sysAdmin": sysAdminUpdatePwd}
		response.Success(c, data)
		return
	}
	response.Failed(c, int(constants.ApiCode.FAILED), "修改密码失败")
}

// 验证管理员是否存在
func (s SysAdminServiceImpl) checkAdminIsExists(c *gin.Context, Id int) {
	adminId := dao.GetSysAdminById(Id).AdminId
	if adminId <= 0 {
		response.Failed(c, int(constants.ApiCode.FAILED), "未知管理员")
		return
	}
}

var sysAdminService = SysAdminServiceImpl{}

func SysAdminService() ISysAdminService {
	return &sysAdminService
}
